package com.qixin.util.MybatisPlus;

import org.springframework.util.ResourceUtils;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 生成前端页面
 * Created by 张子艺 on 2018/10/12.
 */
public class MyGenerator {

    public static String URL = "jdbc:mysql://localhost:3306/charge?serverTimezone=GMT";
    public static String USERNAME = "root";
    public static String PASSWORD = "root";

    // TODO: 2018/10/12 需要生成的页面  表名   数据库名
    public static void main(String[] args) throws IOException, SQLException {
        gent("we_charging", "charge");
    }






    //读取模板
    public static String redFile(File file) {
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    //输出文件
    public static void outFile(String text) throws IOException {
        try {

            File dir = new File("C:\\gent");
            File file = new File("C:\\gent\\gent.ftl");
            if (!dir.exists() && !file.isDirectory()) {
                dir.mkdir();
            }
            //if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            //true = append file
            FileWriter fileWritter = new FileWriter(file);
            fileWritter.write(text);
            fileWritter.flush();
            fileWritter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //查询表名
    public static List<Generator> dataBase(String tableName, String dataBaseName) throws SQLException {

        List<Generator> list = new ArrayList<>();
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(
                " SELECT " +
                        " a.table_comment as table_comment," +
                        " b.COLUMN_NAME  as column_name, " +
                        " b.column_comment   as column_comment" +
                        " FROM " +
                        " information_schema.TABLES a " +
                        "LEFT JOIN information_schema.COLUMNS b ON a.table_name = b.TABLE_NAME " +
                        " WHERE " +
                        " a.table_schema = '"+dataBaseName+"' " +
                        "and a.table_name = '"+tableName+"'    " +
                        " ORDER BY " +
                        "  a.table_name "
        );

        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            Generator generator = new Generator();
            generator.setColumn(resultSet.getString("column_name"));
            generator.setComment(resultSet.getString("column_comment"));
            generator.setTable_comment(resultSet.getString("table_comment"));
            list.add(generator);
        }
        connection.close();
        preparedStatement.close();
        return list;
    }

    public static void gent(String tableName, String dataBaseName) {
        List<Generator> generators = new ArrayList<>();
        try {
            generators = dataBase(tableName, dataBaseName);
            //下划线转驼峰
            for (int n = 0; n < generators.size(); n++) {
                generators.get(n).setColumn(UnderlineToHump(generators.get(n).getColumn()));
            }
            //读取模板
            File file = ResourceUtils.getFile("classpath:gentFile\\gent.html");
            String text = redFile(file);
            String tableText = "";
            // TODO: 2018/10/12  这里为替换变量的地方 本次替换的是表格 第一行表格不需要逗号  后续循环需要逗号 
            for (int i = 0; i < generators.size(); i++) {
                if (i == 0) {
                    tableText += "{field:'" + generators.get(i).getColumn() + "', title: '" + generators.get(i).getComment() + "',align:'center',width:180}";
                } else {
                    tableText += "\r\n" + ",{field:'" + generators.get(i).getColumn() + "', title: '" + generators.get(i).getComment() + "',align:'center',width:180}";
                }
            }
            text = text.replace("{<Table>}", tableText);
            text = text.replace("{<TableName>}", generators.get(0).getTable_comment());
            outFile(text);
        } catch (SQLException e) {
            e.printStackTrace();
            System.err.println("出现sql异常");
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("出现sql异常");
        }
    }

    //下划线后一个字母转为大写
    public static String UnderlineToHump(String para) {
        StringBuilder result = new StringBuilder();
        String a[] = para.split("_");
        for (String s : a) {
            if (result.length() == 0) {
                result.append(s.toLowerCase());
            } else {
                result.append(s.substring(0, 1).toUpperCase());
                result.append(s.substring(1).toLowerCase());
            }
        }
        return result.toString();
    }


}
